<template>
  <div class="container">
    <!-- 面包屑 -->
    <SubBread />
    <!-- 筛选 -->
    <SubFilter @filter-sort='sortChangeFn'/>
    <!-- 结果列表 -->
    <div class="goods-list">
      <!-- 排序 -->
      <SubSort @sortChange="sortChangeFn" />
      <!-- 列表 -->
      <ul>
        <li v-for="item in list" :key="item.id">
          <GoodsItem :goods="item" />
        </li>
      </ul>
      <!-- 加载/加载完成 -->
      <XtxInfiniteLoading
        :loading="loading"
        :finished="finished"
        @load="onLoad"
      />
    </div>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
import SubSort from './components/sub-sort'
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import GoodsItem from './components/goods-item.vue'
import { findSubCategoryGoods } from '@/api/category.js'
import { useRoute } from 'vue-router'
export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    GoodsItem
  },
  setup () {
    const route = useRoute()
    // 分页数据
    let data = {
      page: 1,
      pageSize: 20
    }
    // 数据列表
    const list = ref([])
    // 正在加载中
    const loading = ref(false)
    // 加载完成
    const finished = ref(false)
    // 子组件传过来的加载事件
    const onLoad = async () => {
      // 加载前
      loading.value = true
      // 加载中
      const { result } = await findSubCategoryGoods(data)
      // 加载后
      loading.value = false
      // 判断是否加载完毕
      if (result.items.length < data.pageSize) {
        finished.value = true
      }
      // 将获取的数据存储
      list.value.push(...result.items)
      // 页码增加1
      data.page++
    }
    // 监听路由变化
    watch(
      () => route.params.id,
      (id) => {
        // 清空数据
        list.value = []
        // 清除加载完毕状态
        finished.value = false
        // 重置数据
        data = {
          page: 1,
          pageSize: 20,
          // 添加id属性
          categoryId: id
        }
        // 加载数据
        onLoad()
      },
      { immediate: true }
    )
    // 接收子组件传过来的变更的数据
    const sortChangeFn = (val) => {
      // 清空数据
      list.value = []
      // 清除加载完毕状态
      finished.value = false
      // 拼接数据，且重置页码为1
      data = { ...data, ...val, page: 1 }
      // 加载数据
      onLoad()
    }

    return { sortChangeFn, loading, finished, onLoad, list }
  }
}
</script>
<style scoped lang='less'>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
